package fr.admf.phaselistener;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseListener;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;

import fr.adfm.dto.MemberDto;
import fr.adfm.managedbean.SessionManager;
import fr.adfm.service.facade.Facade;

@Component
@Scope("session")
public class LoginListener implements PhaseListener, Serializable {

	@Override
	public void beforePhase(PhaseEvent pe) 	  {	
		 if (pe.getPhaseId() == PhaseId.RENDER_RESPONSE) {

			String referer = pe.getFacesContext().getExternalContext().getRequestHeaderMap().get("referer"); 
			
			if(referer == null) {
				FacesContext fc = pe.getFacesContext();
				NavigationHandler nh = fc.getApplication().getNavigationHandler();
				nh.handleNavigation(fc, null, "index");
				return;
			}
			if ("http://localhost:8080/ConfidentialSales-web/".equals(referer) 
				|| "http://localhost:8080/ConfidentialSales-web/login.xhtml".equals(referer) 
				|| "http://localhost:8080/ConfidentialSales-web/index.xhtml".equals(referer)) {
				return;
			} else {	
				MemberDto memberDto = (MemberDto) pe.getFacesContext().getExternalContext().getSessionMap().get("memberDto");
				if(memberDto  == null) {
					FacesContext fc = pe.getFacesContext();
					NavigationHandler nh = fc.getApplication().getNavigationHandler();
					nh.handleNavigation(fc, null, "login");
				}
			}
		}
	}

	@Override
	public void afterPhase(PhaseEvent pe) { 
	}

	@Override
	public PhaseId getPhaseId() {  
		return PhaseId.ANY_PHASE;
	}
}
